package com.twetec.cms.adapter.pc.backend.controller.website;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.twetec.cms.adapter.pc.backend.response.R;
import com.twetec.cms.adapter.pc.backend.response.ResultCodeMsgEnum;
import com.twetec.cms.common.constant.CmsSiteArticlePermissionEnum;
import com.twetec.cms.common.constant.FileConst;
import com.twetec.cms.common.constant.StaticHtmlStatusEnum;
import com.twetec.cms.common.constant.StaticHtmlTypeEnum;
import com.twetec.cms.common.util.validate.ValidateUtil;
import com.twetec.cms.model.po.system.CmsMenuPO;
import com.twetec.cms.model.po.system.CmsUserRolePO;
import com.twetec.cms.model.po.system.StaticLogPO;
import com.twetec.cms.model.po.user.UserPO;
import com.twetec.cms.model.po.website.SitePO;
import com.twetec.cms.model.vo.website.*;
import com.twetec.cms.service.file.FastdfsFileService;
import com.twetec.cms.service.system.CmsMenuService;
import com.twetec.cms.service.system.CmsRoleMenuService;
import com.twetec.cms.service.system.CmsUserRoleService;
import com.twetec.cms.service.system.StaticLogService;
import com.twetec.cms.service.ucenter.UserService;
import com.twetec.cms.service.website.SiteClusterServerService;
import com.twetec.cms.service.website.SiteService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Api(tags = "站点管理")
@RestController
@RequestMapping("/website/site")
public class SiteController {

    @Autowired
    private SiteService siteService;

    @Autowired
    private UserService userService;

    @Autowired
    private FastdfsFileService fastdfsFileService;

    @Autowired
    private CmsMenuService cmsMenuService;

    @Autowired
    private CmsUserRoleService cmsUserRoleService;

    @Autowired
    private CmsRoleMenuService cmsRoleMenuService;

    @Autowired
    private StaticHtmlController staticHtmlController;

    @Value("${twetec.resource.preview-root-path}")
    private String previewPath;

    @Value("${twetec.resource.preview-root-url}")
    private String previewUrl;

    @Value("${twetec.resource.storage-root-path}")
    private String storagePath;

    @Autowired
    private SiteClusterServerService siteClusterServerService;

    @Autowired
    private StaticLogService staticLogService;

//    private static final String ARTICLE_COPY_BY_ID = "website:article:create";


    private static final String UPLOAD_PATH = System.getProperty("user.dir");

//    private static final String UPLOAD_PATH = System.getProperty("user.dir");

    @ApiOperation(value = "更新站点信息", notes = "更新站点信息")
    @PutMapping("/update-by-id")
    public R updateById(@ApiParam(value = "站点id", required = true, example = "123456789") @RequestParam(required = false) Long id,
                        @ApiParam(value = "站点名称", required = true, example = "厦门市总工会") @RequestParam(required = false) String name,
                        @ApiParam(value = "站点域名地址（数字，大小写英文字母，下划线和点的组合，不包含http://）", required = true, example = "www.baidu.com") @RequestParam(required = false) String domainUrl,
                        @ApiParam(value = "展示排序序号", required = true, example = "1") @RequestParam(required = false) Integer sort,
                        @ApiParam(value = "站点logo", required = false, example = "D:\\Project\\站点图片1.jpg") @RequestParam(required = false) String logo,
                        @RequestAttribute("userId") Long userId) {


        // 1. 参数校验
        if (null == id || !ValidateUtil.Number(id)) return R.failureRequestParam().msg("站点id为空或格式不正确");
        if (StringUtils.isEmpty(name) || name.length() > 50) return R.failureRequestParam().msg("站点名称为空或超过50个字符");
        if (StringUtils.isEmpty(domainUrl) /*|| !ValidateUtil.Domain(domainUrl)*/)
            return R.failureRequestParam().msg("站点域名地址为空或格式不正确");
        if (null == sort || !ValidateUtil.Number(sort)) return R.failureRequestParam().msg("序号为空或格式不正确");

        // 2. 更新站点信息
        SitePO sitePO = new SitePO();
        sitePO.setId(id);
        sitePO.setName(name);
        sitePO.setDomainUrl(domainUrl);
        sitePO.setSort(sort);
        sitePO.setModifierId(userId);
        if (StringUtils.isEmpty(logo)) logo = " ";
        System.out.println("*************************" + logo);
        sitePO.setLogo(logo);

        // 更新
        Boolean result = siteService.updateById(sitePO);

        if (result) return R.success().msg("更新成功");
        return R.failure().msg("更新失败");
    }


    @Transactional
    @ApiOperation(value = "新增站点", notes = "新增站点")
    @PostMapping("/create")
    public R create(@ApiParam(value = "站点名称", required = true, example = "厦门市总工会") @RequestParam(required = false) String name,
                    @ApiParam(value = "站点域名地址（数字，大小写英文字母，下划线和点的组合，不包含http://）", required = true, example = "www.baidu.com") @RequestParam(required = false) String domainUrl,
                    @ApiParam(value = "展示排序序号", required = true, example = "1") @RequestParam(required = false) Integer sort,
                    @ApiParam(value = "关键字（字符串用英文逗号隔开）", required = false, example = "工会,站点") @RequestParam(required = false) String seoKeywords,
                    @ApiParam(value = "站点logo", required = false, example = "D:\\Project\\站点图片1.jpg") @RequestParam(required = false) String logo,
                    @RequestAttribute("userId") Long userId) {
        // 请求参数校验
        if (StringUtils.isEmpty(name)) return R.failureRequestParam().msg("站点名称不能为空");
        if (StringUtils.isEmpty(domainUrl) /*|| !ValidateUtil.Domain(domainUrl)*/)
            return R.failureRequestParam().msg("站点域名地址为空或格式不正确");
        if (null == sort || !ValidateUtil.Number(sort)) R.failureRequestParam().msg("序号为空或格式不正确");


        // 进行新增
        SitePO sitePO = new SitePO();
        sitePO.setName(name);
        sitePO.setDomainUrl(domainUrl);
        // seoKeyWords
        sitePO.setSeoKeywords(seoKeywords);
        sitePO.setSort(sort);
        sitePO.setCreatorId(userId);
        sitePO.setModifierId(userId);

        // 站点logo
        if (StringUtils.isEmpty(logo)) logo = " ";
        System.out.println("*************************" + logo);
        sitePO.setLogo(logo);

        boolean result = siteService.save(sitePO);

        if (!result) {
            return R.failure().msg("新增失败");
        }

        //  添加站点权限
        ArrayList<CmsMenuPO> cmsMenuPOS = cmsMenuService.addSitePermission(sitePO.getId(), name, userId);

        // 权限与用户的所有角色关联
        // 获取所有创建的站点的权限
        ArrayList<Long> menuIdList = new ArrayList<>();
        for (CmsMenuPO cmsMenuPO : cmsMenuPOS) {
            menuIdList.add(cmsMenuPO.getId());
        }
        // 获取用户关联的所有角色
        QueryWrapper<CmsUserRolePO> cmsUserRolePOQueryWrapper = new QueryWrapper<>();
        cmsUserRolePOQueryWrapper.eq("user_id", userId);
        List<CmsUserRolePO> cmsUserRolePOList = cmsUserRoleService.list(cmsUserRolePOQueryWrapper);
        if (null == cmsUserRolePOList || cmsUserRolePOList.size() == 0) {
            return R.failure().msg("权限添加失败");
        }
        StringBuffer roleIds = new StringBuffer();
        for (CmsUserRolePO userRolePO : cmsUserRolePOList) {
            roleIds.append(userRolePO.getRoleId());
            roleIds.append(",");
        }
        String roleIdStr = roleIds.substring(0, roleIds.lastIndexOf(","));
        boolean menuRelative = cmsRoleMenuService.addRoleMenuRelative(roleIdStr, menuIdList);

        // 清除所有用户存在redis中的权限
        boolean deleteUserPermission = cmsRoleMenuService.deleteUserPermission();

        return menuRelative ? R.success().msg("新增成功") : R.failure().msg("新增失败");
    }


    @ApiOperation(value = "站点分页列表展示与搜索", notes = "站点分页列表展示与搜索")
    @GetMapping("/page-search-list")
    public R<SitePageListVO> pageSearchList(@ApiParam(value = "站点名称", required = false, example = "厦门市总工会") @RequestParam(required = false) String name,
                                            @ApiParam(value = "站点域名地址（数字，大小写英文字母，下划线和点的组合，不包含http://）", required = false, example = "www.baidu.com") @RequestParam(required = false) String domainUrl,
                                            @ApiParam(value = "更新人", required = false, example = "张三") @RequestParam(required = false) String modifierName,
                                            @ApiParam(value = "根据更新时间搜索的开始时间（10位时间戳）", required = false, example = "1234567891") @RequestParam(required = false) Date gmtModifiedStart,
                                            @ApiParam(value = "根据更新时间搜索的结束时间（10位时间戳）", required = false, example = "1231231231") @RequestParam(required = false) Date gmtModifiedEnd,
                                            @ApiParam(value = "seo关键字(字符串类型用英文逗号隔开)", required = false, example = "厦门,工会,门户") @RequestParam(required = false) String seoKeywords,
                                            @ApiParam(value = "seo标题", required = false, example = "厦门市工会门户网站") @RequestParam(required = false) String seoTitle,
                                            @ApiParam(value = "seo描述", required = false, example = "厦门市工会门户网站") @RequestParam(required = false) String seoDesc,
                                            @ApiParam(value = "要访问的页码", required = true, example = "1") @RequestParam(required = false) Integer page,
                                            @ApiParam(value = "页面容量", required = true, example = "10") @RequestParam(required = false) Integer limit,
                                            @RequestAttribute("userId") Long userId) {

        if (null == page || !ValidateUtil.Number(page) || page < 0) return R.failureRequestParam().msg("页码为空或格式不正确");
        if (null == limit || !ValidateUtil.Number(limit) || limit < 0)
            return R.failureRequestParam().msg("页条目数为空或格式不正确");

        // 查询用户对应的角色集合
        QueryWrapper<CmsUserRolePO> cmsUserRolePOQueryWrapper = new QueryWrapper<>();
        cmsUserRolePOQueryWrapper.lambda().eq(CmsUserRolePO::getUserId, userId);
        List<CmsUserRolePO> list = cmsUserRoleService.list(cmsUserRolePOQueryWrapper);
        ArrayList<Long> roleIdList = new ArrayList<>();
        for (CmsUserRolePO userRolePO : list) {
            roleIdList.add(userRolePO.getRoleId());
        }
        // 获取菜单类型为站点的
        List<CmsMenuPO> cmsMenuSitePOList = cmsMenuService.getAllRolePermission(roleIdList, "ZHAN_DIAN");

        // 获取有权限的站点id
        ArrayList<Long> siteIdList = new ArrayList<>();
        for (CmsMenuPO cmsMenuPO : cmsMenuSitePOList) {
            if (siteIdList.contains(cmsMenuPO.getSiteId())) continue;
            siteIdList.add(cmsMenuPO.getSiteId());
        }

        SitePageListVO sitePageListVO = new SitePageListVO();

        // 设置查询条件
        QueryWrapper<SitePO> queryWrapper = new QueryWrapper<>();

        queryWrapper.in("ID", siteIdList);

        // 关键字
        if (StringUtils.isNotEmpty(seoKeywords)) {
            queryWrapper.like("SEO_KEYWORDS", seoKeywords);
        }

        // seo标题
        if (StringUtils.isNotEmpty(seoTitle)) queryWrapper.like("SEO_TITLE", seoTitle);

        // seo描述
        if (StringUtils.isNotEmpty(seoDesc)) queryWrapper.like("SEO_DESC", seoDesc);

        // 站点名称
        if (StringUtils.isNotEmpty(name)) {
            queryWrapper.like("NAME", name);
        }

        // 站点域名
        if (StringUtils.isNotEmpty(domainUrl)) {
            queryWrapper.like("DOMAIN_URL", domainUrl);
        }

        // 根据更新人name查询更新人id
        List<UserPO> userPOList = null;
        if (StringUtils.isNotEmpty(modifierName)) {
            QueryWrapper<UserPO> userWrapper = new QueryWrapper<>();
            // userPOQueryWrapper1.select("ID");
            userWrapper.like("NAME", modifierName);
            userPOList = userService.list(userWrapper);
        }
        // 当更新人ID查询结果不为空，且存储得有数据的时候
        if (userPOList != null && userPOList.size() > 0) {
            ArrayList<Long> userIdList = new ArrayList<>();
            for (UserPO userPO : userPOList) {
                userIdList.add(userPO.getId());
            }
            queryWrapper.in("MODIFIER_ID", userIdList);
        }
        // 当更新人id查询结果为空，但是传入的更新人姓名不为空的时候，表示表中没有对应的操作人，直接返回空集合
        if ((userPOList == null || userPOList.size() == 0) && StringUtils.isNotEmpty(modifierName)) {
            sitePageListVO.setPage(page);
            sitePageListVO.setLimit(limit);
            sitePageListVO.setTotal(0);
            sitePageListVO.setList(new ArrayList<SiteVO>());
            return R.success().data(sitePageListVO);
        }

        // 更新时间
        if (gmtModifiedStart != null && gmtModifiedEnd != null) {
            queryWrapper.between("GMT_MODIFIED", gmtModifiedStart, gmtModifiedEnd);
        } else if (null != gmtModifiedStart) {
            queryWrapper.gt("GMT_MODIFIED", gmtModifiedStart);
        } else if (null != gmtModifiedEnd) {
            queryWrapper.lt("GMT_MODIFIED", gmtModifiedEnd);
        }

        // 未被回收的
        queryWrapper.eq("IS_RECOVERY", 0);

        // 排序
        queryWrapper.orderByDesc("GMT_MODIFIED");
        queryWrapper.orderByAsc("SORT");
        // 执行查询
        Page<SitePO> sitePOPage = siteService.page(new Page<>(page, limit), queryWrapper);

        // 设置返回数据

        sitePageListVO.setTotal((int) sitePOPage.getTotal());
        sitePageListVO.setPage((int) sitePOPage.getCurrent());
        sitePageListVO.setLimit((int) sitePOPage.getSize());

        // 获取查询到的站点记录
        List<SitePO> records = sitePOPage.getRecords();

        List<SiteVO> siteVOList = new ArrayList<>();
        // 遍历站点记录，复制属性到VO并添加更新人名字
        for (SitePO sitePO : records) {
            SiteVO siteVO = new SiteVO();
            BeanUtils.copyProperties(sitePO, siteVO);

            // 查询更新人姓名
            QueryWrapper<UserPO> modifierWrapper = new QueryWrapper<>();
            modifierWrapper.eq("ID", sitePO.getModifierId());
            UserPO modifierPO = userService.getOne(modifierWrapper);
            siteVO.setModifierName(modifierPO.getName());

            siteVOList.add(siteVO);
        }
        sitePageListVO.setList(siteVOList);
        return R.success().data(sitePageListVO);
    }


    @ApiOperation(value = "批量回收站点", notes = "批量回收站点")
    @PutMapping("/remove-by-ids")
    public R removeByIds(@ApiParam(value = "站点id的字符串用英文逗号分隔", required = true, example = "1234567890,1234567890") @RequestParam(required = false) String ids,
                         @RequestAttribute("userId") Long userId) {

        if (null == ids || StringUtils.isEmpty(ids)) return R.failure().msg("请选择你要回收的站点id");

        String[] idSplit = ids.split(",");
        ArrayList<Long> idList = new ArrayList<>();
        for (String idString : idSplit) {
            Long id = Long.valueOf(idString);
            idList.add(id);
        }

        // 批量回收站点
        UpdateWrapper<SitePO> wrapper = new UpdateWrapper<>();
        wrapper.set("MODIFIER_ID", userId);
        wrapper.set("IS_RECOVERY", 1);
        wrapper.in("ID", idList);
        boolean result = siteService.update(new SitePO(), wrapper);

        if (!result) return R.failure().msg("批量回收失败");

        // TODO ：： 删除站点的菜单权限
        boolean removeSitePermission = cmsMenuService.removeSitePermission(idList);
        if (!removeSitePermission) return R.failure().msg("回收失败");

        return R.success().msg("批量回收成功");
    }


    @Transactional
    @ApiOperation(value = "根据id回收站点", notes = "根据id回收站点")
    @PutMapping("/remove-by-id")
    public R removeById(@ApiParam(value = "站点id", required = true, example = "1234567890") @RequestParam(required = false) Long id,
                        @RequestAttribute("userId") Long userId) {

        if (null == id || !ValidateUtil.Number(id) || id < 0) return R.failure().msg("id格式不正确");

        // 根据ID回收站点
        SitePO sitePO = new SitePO();
        sitePO.setModifierId(userId);
        sitePO.setId(id);
        sitePO.setRecovery(1);
        boolean result = siteService.updateById(sitePO);
        if (!result) return R.failure().msg("回收失败");

        ArrayList<Long> longs = new ArrayList<>();
        longs.add(id);
        // TODO ：： 删除站点的菜单权限
        boolean removeSitePermission = cmsMenuService.removeSitePermission(longs);
        if (!removeSitePermission) return R.failure().msg("回收失败");

        return R.success().msg("回收成功");
    }


    //    @SitePermission(ARTICLE_COPY_BY_ID)
    @ApiOperation(value = "根据id获取站点信息", notes = "根据id获取站点信息")
    @GetMapping("/get-by-id")
    public R<SiteItemVO> getById(@ApiParam(value = "站点id", required = true, example = "1234567891") @RequestParam(required = false) Long id) {
        CmsSiteArticlePermissionEnum.ARTICLE_COPY_BY_ID.getValue();
        // 参数校验
        if (null == id || !ValidateUtil.Number(id) || id <= 0) return R.failureRequestParam().msg("id为空或格式不正确");

        // 进行查询
        SitePO sitePO = siteService.getById(id);
        if (sitePO == null) return R.resultCodeMsg(ResultCodeMsgEnum.DATA_NOT_EXIST);

        // 转化为VO
        SiteItemVO siteItemVO = new SiteItemVO();
        BeanUtils.copyProperties(sitePO, siteItemVO);

        UserPO modifierPO = userService.getById(sitePO.getModifierId());
        siteItemVO.setModifierName(modifierPO.getName());

        return R.success().data(siteItemVO);
    }

    @ApiOperation(value = "回收站站点分页列表展示与搜索")
    @GetMapping("/page-search-list-recovery")
    public R<SitePageListVO> pageSearchListRecovery(@ApiParam(value = "站点名称", required = false, example = "厦门市总工会") @RequestParam(required = false) String name,
                                                    @ApiParam(value = "站点域名地址（数字，大小写英文字母，下划线和点的组合，不包含http://）", required = false, example = "http://www.baidu.com") @RequestParam(required = false) String domainUrl,
                                                    @ApiParam(value = "更新人", required = false, example = "张正铭") @RequestParam(required = false) String modifierName,
                                                    @ApiParam(value = "根据更新时间搜索的开始时间（10位时间戳）", required = false, example = "1234567891") @RequestParam(required = false) Date gmtModifiedStart,
                                                    @ApiParam(value = "根据更新时间搜索的结束时间（10位时间戳）", required = false, example = "1231231231") @RequestParam(required = false) Date gmtModifiedEnd,
                                                    @ApiParam(value = "seo关键字(字符串类型用英文逗号隔开)", required = false, example = "厦门,工会,门户") @RequestParam(required = false) String seoKeywords,
                                                    @ApiParam(value = "seo标题", required = false, example = "厦门市工会门户网站") @RequestParam(required = false) String seoTitle,
                                                    @ApiParam(value = "seo描述", required = false, example = "厦门市工会门户网站") @RequestParam(required = false) String seoDesc,
                                                    @ApiParam(value = "要访问的页码", required = true, example = "1") @RequestParam(required = false) Integer page,
                                                    @ApiParam(value = "页面容量", required = true, example = "10") @RequestParam(required = false) Integer limit) {

        if (page == null && page <= 0) return R.failureRequestParam().msg("页码不能为空");
        if (limit == null && limit <= 0) return R.failureRequestParam().msg("页条目数不能为空");

        SitePageListVO sitePageListVO = new SitePageListVO();
        // 设置查询条件
        QueryWrapper<SitePO> wrapper = new QueryWrapper<>();

        // 关键字
        if (StringUtils.isNotEmpty(seoKeywords)) {
            wrapper.like("SEO_KEYWORDS", seoKeywords);
        }

        // seo标题
        if (StringUtils.isNotEmpty(seoTitle)) wrapper.like("SEO_TITLE", seoTitle);

        // seo描述
        if (StringUtils.isNotEmpty(seoDesc)) wrapper.like("SEO_DESC", seoDesc);

        // 站点名称判断
        if (StringUtils.isNotEmpty(name)) wrapper.like("NAME", name);
        // 站点地址判断
        if (StringUtils.isNotEmpty(domainUrl)) wrapper.like("DOMAIN_URL", domainUrl);
        // 根据更新人name查询更新人id
        List<UserPO> userPOList = null;
        if (StringUtils.isNotEmpty(modifierName)) {
            QueryWrapper<UserPO> userWrapper = new QueryWrapper<>();
            // userPOQueryWrapper1.select("ID");
            userWrapper.like("NAME", modifierName);
            userPOList = userService.list(userWrapper);
        }
        // 更新人ID
        if (userPOList != null && userPOList.size() > 0) {
            ArrayList<Long> userIdList = new ArrayList<>();
            for (UserPO userPO : userPOList) {
                userIdList.add(userPO.getId());
            }
            wrapper.in("MODIFIER_ID", userIdList);
        }
        // 当更新人id查询结果为空，但是传入的更新人姓名不为空的时候，表示表中没有对应的操作人，直接返回空集合
        if ((userPOList == null || userPOList.size() == 0) && StringUtils.isNotEmpty(modifierName)) {
            sitePageListVO.setPage(page);
            sitePageListVO.setLimit(limit);
            sitePageListVO.setTotal(0);
            sitePageListVO.setList(new ArrayList<SiteVO>());
            return R.success().data(sitePageListVO);
        }

        // 更新时间
        if (gmtModifiedStart != null && gmtModifiedEnd != null) {
            wrapper.between("GMT_MODIFIED", gmtModifiedStart, gmtModifiedEnd);
        } else if (gmtModifiedStart != null) {
            wrapper.ge("GMT_MODIFIED", gmtModifiedStart);
        } else if (gmtModifiedEnd != null) {
            wrapper.le("GMT_MODIFIED", gmtModifiedEnd);
        }
        wrapper.eq("IS_RECOVERY", 1);
        // 根据更新时间倒序排列
        wrapper.orderByDesc("GMT_MODIFIED");
        wrapper.orderByAsc("SORT");

        // 分页查询
        Page<SitePO> sitePOPage = siteService.page(new Page<>(page, limit), wrapper);
        // 返回给前端的VO  sitePOPage-->vo

        sitePageListVO.setPage((int) sitePOPage.getCurrent());
        sitePageListVO.setLimit((int) sitePOPage.getSize());
        sitePageListVO.setTotal((int) sitePOPage.getTotal());
        // 遍历sitePOPage里的records
        List<SitePO> records = sitePOPage.getRecords();
        // 创建一个存放records的集合
        ArrayList<SiteVO> siteVOArrayList = new ArrayList<>();
        // 遍历存放records的集合
        for (SitePO sitePO : records) {
            SiteVO siteVO = new SiteVO();
            BeanUtils.copyProperties(sitePO, siteVO);

            // 如果传入的查询参数有modifierName，并且也查到了对应的user对象。就将更新人姓名设为传入的更新人。
            // 如果传入的查询参数没有modifierName更新人姓名 通过sitePO.getId()传入条件构造器查找modifierName
            UserPO userModifierPO = userService.getById(sitePO.getModifierId());
            siteVO.setModifierName(userModifierPO.getName());
            // 没有创建者的信息
            UserPO userCreatePO = userService.getById(sitePO.getCreatorId());

            // 将siteVO添加到存放records的集合中-->siteVOArrayList
            siteVOArrayList.add(siteVO);
        }
        // 将存放records的集合放到返回给前端的VO，已经有的属性前面都复制过去了
        sitePageListVO.setList(siteVOArrayList);

        return R.success().data(sitePageListVO);
    }

    @ApiOperation(value = "根据id恢复", notes = "根据id恢复")
    @PutMapping("/recovery-by-id")
    public R recoveryById(@ApiParam(value = "id", required = true, example = "12312313123") @RequestParam(required = false) Long id,
                          @RequestAttribute("userId") Long userId) {

        // 校验id
        if (id == null || !ValidateUtil.Number(id)) {
            return R.failureRequestParam().msg("id输入有误");
        }

        // 处理是否回收
        SitePO sitePO = new SitePO();
        UpdateWrapper<SitePO> sitePOUpdateWrapper = new UpdateWrapper<>();
        // 设置id
        sitePOUpdateWrapper.eq("ID", id);
        // 设置是否回收 0恢复 1回收
        sitePOUpdateWrapper.set("IS_RECOVERY", 0);
        // 设置更新人id
        sitePOUpdateWrapper.set("MODIFIER_ID", userId);
        // 更新并返回
        boolean result = siteService.update(sitePO, sitePOUpdateWrapper);

        if (!result) return R.failure().msg("恢复失败");

        // 回复站点的菜单权限
        ArrayList<Long> longs = new ArrayList<>();
        longs.add(id);
        boolean recoverySitePermission = cmsMenuService.recoverySitePermission(longs);
        if (!recoverySitePermission) return R.failure().msg("恢复失败");

        return R.success().msg("恢复成功");

    }

    @ApiOperation(value = "根据id批量恢复", notes = "根据id批量恢复")
    @PutMapping("/recovery-by-ids")
    public R recoveryByIds(@ApiParam(value = "站点id的字符串用英文逗号分隔", required = true, example = "12312313123,12312313123") @RequestParam(required = false) String ids,
                           @RequestAttribute("userId") Long userId) {

        // 校验idList
        if (null == ids || StringUtils.isEmpty(ids)) return R.failure().msg("请选择你要恢复的站点id");

        String[] idSplit = ids.split(",");
        ArrayList<Long> idList = new ArrayList<>();
        for (String idString : idSplit) {
            Long id = Long.valueOf(idString);
            idList.add(id);
        }

        // 通过改造更新的条件构造器进行批量操作
        SitePO sitePO = new SitePO();
        UpdateWrapper<SitePO> sitePOUpdateWrapper = new UpdateWrapper<>();
        sitePOUpdateWrapper.set("IS_RECOVERY", 0);
        sitePOUpdateWrapper.in("ID", idList);
        sitePOUpdateWrapper.set("MODIFIER_ID", userId);
        boolean result = siteService.update(sitePO, sitePOUpdateWrapper);

        if (!result) return R.failure().msg("批量恢复失败");
        // 恢复站点的菜单权限
        boolean recoverySitePermission = cmsMenuService.recoverySitePermission(idList);
        if (!recoverySitePermission) return R.failure().msg("批量恢复失败");

        return R.success().msg("批量恢复成功");

    }

    @ApiOperation(value = "根据站点id获取seo", notes = "根据站点id获取seo")
    @GetMapping("/get-seo-by-site-id")
    public R<SeoVO> getSeoBySiteId(@ApiParam(value = "站点id", required = true, example = "1440511661143220226") @RequestParam(required = false) Long siteId) {

        // 参数校验
        if (null == siteId && !ValidateUtil.Number(siteId)) R.failureRequestParam().msg("站点id为空或格式不正确");

        // 查询
        SitePO sitePO = siteService.getById(siteId);

        if (sitePO != null) {
            SeoVO seoVO = new SeoVO();
            BeanUtils.copyProperties(sitePO, seoVO);
            return R.success().data(seoVO);
        }
        return R.resultCodeMsg(ResultCodeMsgEnum.DATA_NOT_EXIST);
    }

    @ApiOperation(value = "根据站点id更新seo", notes = "根据站点id更新seo")
    @PutMapping("/update-seo-by-site-id")
    public R<SeoVO> updateSeoBySiteId(@ApiParam(value = "站点id", required = true, example = "1440511661143220226") @RequestParam(required = false) Long siteId,
                                      @ApiParam(value = "标题", required = true, example = "厦门市工会") @RequestParam(required = false) String seoTitle,
                                      @ApiParam(value = "关键字（字符串类型，多个关键字之间用英文逗号隔开）", required = true, example = "厦门,湖里,工会,站点") @RequestParam(required = false) String seoKeywords,
                                      @ApiParam(value = "描述", required = true, example = "厦门市湖里区工会站点") @RequestParam(required = false) String seoDesc,
                                      @RequestAttribute("userId") Long userId) {

        // 参数校验
        if (siteId == null || !ValidateUtil.Number(siteId)) return R.failureRequestParam().msg("站点id为空或格式不正确");
        if (StringUtils.isEmpty(seoTitle)) return R.failureRequestParam().msg("seo标题不能为空");
        if (StringUtils.isEmpty(seoKeywords)) return R.failureRequestParam().msg("seo关键字不能为空");
        if (StringUtils.isEmpty(seoDesc)) return R.failureRequestParam().msg("seo描述不能为空");

        // 更新
        SitePO sitePO = new SitePO();
        sitePO.setId(siteId);
        sitePO.setSeoTitle(seoTitle);
        sitePO.setSeoKeywords(seoKeywords);
        sitePO.setSeoDesc(seoDesc);
        sitePO.setModifierId(userId);
        //进行更新
        boolean result = siteService.updateById(sitePO);

        if (result) return R.success().msg("更新成功");
        return R.failure().msg("更新失败");
    }


    @ApiOperation(value = "站点logo上传", notes = "站点logo上传")
    @PostMapping("/upload-logo")
    public R<ImageFileNameVO> uploadLogo(
            @ApiParam(value = "file", required = true, example = "1") @RequestParam(required = false) MultipartFile file) throws IOException {

        // 校验上传文件是否为空
        if (null == file) return R.failureRequestParam().msg("logo文件参数为空");

        // file.getOriginalFilename()得到上传时的文件名(仅返回文件名,并不会包含路径) 并校验是否是图片
        if (!ValidateUtil.isPicture(file.getOriginalFilename())) return R.failureRequestParam().msg("该文件不是图片");

        // file.getSize()以字节为单位返回指定文件的大小
        if (file.getSize() > FileConst.UPLOAD_LOGO_PICTURE_SIZE)
            return R.failureRequestParam().msg("图片大小不能超过" + FileConst.UPLOAD_LOGO_PICTURE_SIZE + "M");
        String fileUrl = fastdfsFileService.uploadSiteLogo(file);

        // 失败
        if (null == fileUrl) return R.failure();

        // 返回文件路径
        ImageFileNameVO imageFileNameVO = new ImageFileNameVO();
        imageFileNameVO.setFileUrl(fileUrl);
        return R.success().data(imageFileNameVO);
    }


    @ApiOperation(value = "预览PC端站点渲染内容", notes = "预览PC端站点首页渲染内容")
    @GetMapping("/get-pc-template-render-content")
    public R<String> getPCTemplateRenderContent(@ApiParam(value = "站点id", required = true, example = "123456789") @RequestParam(required = false) Long siteId) {
        // 接收参数
        if (siteId == null || !ValidateUtil.Number(siteId) || siteId <= 0)
            return R.failureRequestParam().msg("站点id不能为空");

        QueryWrapper<StaticLogPO> staticLogPOQueryWrapper = new QueryWrapper<>();
        staticLogPOQueryWrapper.eq("SITE_ID", siteId);
        staticLogPOQueryWrapper.eq("STATUS", StaticHtmlStatusEnum.JIN_XING_ZHONG.getValue());
        staticLogPOQueryWrapper.eq("STATIC_TYPE", StaticHtmlTypeEnum.HOME.getValue());
        StaticLogPO staticLogPO = staticLogService.getOne(staticLogPOQueryWrapper, false);
        if (null != staticLogPO && null != staticLogPO.getId()) {
            return R.failure().msg("静态化任务正在进行,请稍后再试!");
        }

        // 查询站点信息
        SitePO sitePO = siteService.getById(siteId);
        if (ValidateUtil.isNullOrEmpty(sitePO)) return R.resultCodeMsg(ResultCodeMsgEnum.DATA_NOT_EXIST);

        // 站点的静态文件存储路径
        String storageStaticPath = siteService.getStorageStaticPath(sitePO.getId());
        String pcStorageStaticPath = storageStaticPath + File.separator + "pc";
        String pcStorageHtmlPath = storageStaticPath + File.separator + "pc";

        // 将静态资源和静态页面 拷贝到预览目录下
        // 1、静态文件
//        File previewStaticFile = FileUtil.file(previewPath + File.separator + "static");
//        File sourceStaticFile = FileUtil.file(pcStorageStaticPath + File.separator + "static");
//        FileUtil.copyContent(sourceStaticFile, previewStaticFile, true);
        // 2、静态页面
        File previewHtmlFile = FileUtil.file(previewPath);
        File sourceHtmlFile = FileUtil.file(pcStorageHtmlPath);
        FileUtil.copyContent(sourceHtmlFile, previewHtmlFile, true);

        // 预览路径
        String previewHome = previewUrl + "/index.html";
        return R.success().data(previewHome);
    }


    @ApiOperation(value = "预览H5端站点首页渲染内容", notes = "预览H5端站点首页渲染内容")
    @GetMapping("/get-h5-template-render-content")
    public R<String> getH5TemplateRenderContent(@ApiParam(value = "站点id", required = true, example = "123456789") @RequestParam(required = false) Long siteId) {
        // 接收参数
        if (siteId == null || !ValidateUtil.Number(siteId) || siteId <= 0)
            return R.failureRequestParam().msg("站点id不能为空");

        QueryWrapper<StaticLogPO> staticLogPOQueryWrapper = new QueryWrapper<>();
        staticLogPOQueryWrapper.eq("SITE_ID", siteId);
        staticLogPOQueryWrapper.eq("STATUS", StaticHtmlStatusEnum.JIN_XING_ZHONG.getValue());
        staticLogPOQueryWrapper.eq("STATIC_TYPE", StaticHtmlTypeEnum.HOME.getValue());
        StaticLogPO staticLogPO = staticLogService.getOne(staticLogPOQueryWrapper, false);
        if (null != staticLogPO && null != staticLogPO.getId()) {
            return R.failure().msg("静态化任务正在进行,请稍后再试!");
        }

        // 查询站点信息
        SitePO sitePO = siteService.getById(siteId);
        if (ValidateUtil.isNullOrEmpty(sitePO)) return R.resultCodeMsg(ResultCodeMsgEnum.DATA_NOT_EXIST);

        // 站点的静态文件存储路径
        String storageStaticPath = siteService.getStorageStaticPath(sitePO.getId());
        String pcStorageStaticPath = storageStaticPath + File.separator + "pc" + File.separator + "h5";
        String pcStorageHtmlPath = storageStaticPath + File.separator + "pc" + File.separator + "h5";

        // 将静态资源和静态页面 拷贝到预览目录下
        // 1、静态文件
//        File previewStaticFile = FileUtil.file(previewPath + File.separator + "h5" + File.separator + "static");
//        File sourceStaticFile = FileUtil.file(pcStorageStaticPath + File.separator + "static");
//        FileUtil.copyContent(sourceStaticFile, previewStaticFile, true);
        // 2、静态页面
        File previewHtmlFile = FileUtil.file(previewPath + File.separator + "h5");
        File sourceHtmlFile = FileUtil.file(pcStorageHtmlPath);
        FileUtil.copyContent(sourceHtmlFile, previewHtmlFile, true);

        // 预览路径
        String previewHome = previewUrl + "/h5" + "/index.html";
        return R.success().data(previewHome);
    }



}
